//
//  ScannerView.m
//  NongWanCloud
//
//  Created by YueWen on 2018/3/20.
//  Copyright © 2018年 YueWen. All rights reserved.
//

#import "RITLScannerView.h"

static NSString * ScannerAnimatedPosition = @"RITL_ScannerPositionAnimated";

@interface RITLScannerView ()<AVCaptureMetadataOutputObjectsDelegate>
{
    BOOL _isCallBackData;//是否进行回调数据，避免多次进行数据的回调
}

@property (nonatomic, strong, readwrite)AVCaptureSession *captureSession;
/// 扫描背景图片
@property (nonatomic, strong, readwrite) UIImageView *boxImageView;
/// 输出设备
@property (nonatomic, strong) AVCaptureMetadataOutput *output;
/// 捕捉的设备
@property (nonatomic, strong) AVCaptureDevice *captureDevice;
/// captureLayer
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *videoPreviewLayer;
/// 黑色遮罩layer
@property (nonatomic, strong) CAShapeLayer *shadowLayer;
/// 扫描线
@property (nonatomic, strong) CALayer * scannerLine;

@end

@implementation RITLScannerView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
        _isCallBackData = true;
        self.scannerInset = UIEdgeInsetsMake(166, 52, 0, 52);
        self.backgroundColor = UIColor.blackColor;
        [self buildLayouts];
        [self createRelatedDevice];
    }
    
    return self;
}


- (void)buildLayouts
{
    [self addSubview:self.indicatorView];
    [self.indicatorView mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.center.offset(0);
        make.width.height.mas_equalTo(30);
    }];
}


- (void)layoutSubviews
{
    [super layoutSubviews];
    
    /// 铺满全屏
    NSLog(@"%@",NSStringFromCGRect(self.layer.bounds));
    
    self.videoPreviewLayer.bounds = self.layer.bounds;
    
    self.boxImageView.ritl_originY = self.scannerInset.top;
    self.boxImageView.ritl_originX = self.scannerInset.left;
    self.boxImageView.ritl_width = self.ritl_width - self.scannerInset.left - self.scannerInset.right;
    self.boxImageView.ritl_height = self.boxImageView.ritl_width;

    self.shadowLayer.bounds = self.videoPreviewLayer.bounds;
    self.scannerLine.bounds = CGRectMake(0, 0, self.boxImageView.ritl_width - 14, 2);
    
    if (!self.output) { return; }
    
    // 扫描框
    _output.rectOfInterest = CGRectMake((self.scannerInset.top + 7) / _videoPreviewLayer.ritl_height,
                                        (self.scannerInset.left + 7) / self.videoPreviewLayer.ritl_width,
                                        (self.boxImageView.ritl_height - 14) / self.videoPreviewLayer.ritl_height,
                                        (self.boxImageView.ritl_width - 14) / self.videoPreviewLayer.ritl_width);
    
    printf("\nrectOfInterest = %s\n",NSStringFromCGRect(_output.rectOfInterest).UTF8String);
}


/// 创建相关设备
- (void)createRelatedDevice
{
    NSError *error;
    
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:self.captureDevice error:&error];
    
    if (error) { printf("AVCaptureDeviceInput error = %s\n",error.localizedDescription.UTF8String);return; }
    
    self.output = [AVCaptureMetadataOutput new];
    
    //追加输出流
    [self.captureSession addInput:input];
    [self.captureSession addOutput:self.output];
    
    //设置代理
    [self.output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
    [self.output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    self.videoPreviewLayer.session = self.captureSession;
    
}

#pragma mark -

- (void)start
{
    if (![self.captureSession isRunning] && self.captureSession.inputs.count > 0) {
    
        _isCallBackData = true;
        [self.captureSession startRunning];
        [self captureSessionStartDidSuccess];
    }
}

- (void)stop
{
    if ([self.captureSession isRunning] && self.captureSession.inputs.count > 0) {
        
        _isCallBackData = false;
        [self.captureSession stopRunning];
        [self captureDidStop];
    }
}


- (void)captureSessionStartDidSuccess
{
    [self.indicatorView stopAnimating];
    
    if (!self.videoPreviewLayer.superlayer) {
        [self.layer addSublayer:self.videoPreviewLayer];
    }
    [self addSubview:self.boxImageView];
    
    if (!self.scannerLine.superlayer) {
        [self.boxImageView.layer addSublayer:self.scannerLine];
    }
    
    [self startLineAnimated];//开始动画
}


- (void)captureDidStop
{
    [self.indicatorView stopAnimating];
    [self.videoPreviewLayer removeFromSuperlayer];
    [self.boxImageView removeFromSuperview];
    [self.scannerLine removeFromSuperlayer];
    [self removeAnimated];
}


- (void)startLineAnimated
{
    [self.boxImageView.layer addSublayer:self.scannerLine];
    
    //获得box高度
    CGFloat height = self.boxImageView.ritl_height - 14;
    
    //创建动画
    CABasicAnimation *scanAnimation = [CABasicAnimation animationWithKeyPath:@"position"];
    scanAnimation.toValue = [NSValue valueWithCGPoint:CGPointMake(7, height)];
    
    scanAnimation.duration = 2.0;
    scanAnimation.repeatCount = HUGE_VALF;
    
    [self.scannerLine addAnimation:scanAnimation forKey:ScannerAnimatedPosition];
}


- (void)removeAnimated
{
    [self.scannerLine removeAnimationForKey:ScannerAnimatedPosition];
    self.scannerLine.position = CGPointMake(7, 7);
    [self.scannerLine removeFromSuperlayer];
}

#pragma mark - getter

- (UIActivityIndicatorView *)indicatorView
{
    if (!_indicatorView) {
        _indicatorView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    }
    return _indicatorView;
}


-(AVCaptureDevice *)captureDevice
{
    if (!_captureDevice)
    {
        //初始化捕捉设备（AVCaptureDevice），类型为AVMediaTypeVideo
        _captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    }
    
    return _captureDevice;
}

-(AVCaptureSession *)captureSession
{
    if (!_captureSession)
    {
        _captureSession = [[AVCaptureSession alloc] init];
    }
    
    return _captureSession;
}

-(AVCaptureVideoPreviewLayer *)videoPreviewLayer
{
    if (!_videoPreviewLayer)
    {
        //实例化预览图层
        _videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] init];
        
        //设置预览图层填充方式
        [_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
        _videoPreviewLayer.anchorPoint = CGPointMake(0, 0);
    }
    
    return  _videoPreviewLayer;
}


- (CAShapeLayer *)shadowLayer
{
    if (!_shadowLayer) {
        
        if (CGRectEqualToRect(CGRectZero, _videoPreviewLayer.bounds)) {
            return nil;
        }
        
        //进行贝塞尔遮罩
        UIBezierPath *path = [UIBezierPath bezierPathWithRect:self.videoPreviewLayer.bounds];
        
        CGRect pathRect = CGRectInset(self.boxImageView.bounds, 7, 7);
        pathRect.origin.x = self.scannerInset.left + 7;
        pathRect.origin.y = self.scannerInset.top + 7;
        //透明
        UIBezierPath *clearPath = [UIBezierPath bezierPathWithRect:pathRect];
        //拼接
        [path appendPath:clearPath];
        [path setUsesEvenOddFillRule:true];
        
        _shadowLayer = [CAShapeLayer layer];
        _shadowLayer.anchorPoint = CGPointZero;
        _shadowLayer.path = path.CGPath;
        _shadowLayer.fillRule = kCAFillRuleEvenOdd;
        _shadowLayer.fillColor = UIColor.blackColor.CGColor;
        _shadowLayer.opacity = 0.7;
//        _shadowLayer.backgroundColor = [UIColor.blackColor colorWithAlphaComponent:0.7].CGColor;
        
        [self.videoPreviewLayer addSublayer:_shadowLayer];
    }
    
    return _shadowLayer;
}


- (UIImageView *)boxImageView
{
    if (!_boxImageView) {
        
        _boxImageView = [UIImageView new];
        _boxImageView.image = [[@"scanner_box" ritl_image] resizableImageWithCapInsets:UIEdgeInsetsMake(6, 6, 6, 6) resizingMode:UIImageResizingModeStretch];
    }
    
    return _boxImageView;
}


-(CALayer *)scannerLine
{
    if (!_scannerLine)
    {
        _scannerLine = [CALayer layer];
        _scannerLine.position = CGPointMake(7, 7);
        _scannerLine.anchorPoint = CGPointZero;
        _scannerLine.contents = (__bridge id _Nullable)([UIImage imageNamed:@"scanner_line"].CGImage);
    }
    
    return _scannerLine;
}



- (void)setScannerInset:(UIEdgeInsets)scannerInset
{
    if (UIEdgeInsetsEqualToEdgeInsets(scannerInset, _scannerInset)) { return; }
    
    _scannerInset = scannerInset;
    
    //重新布局
    [self layoutIfNeeded];
}


#pragma mark - <AVCaptureMetadataOutputObjectsDelegate>

- (void)captureOutput:(AVCaptureOutput *)output didOutputMetadataObjects:(NSArray<__kindof AVMetadataObject *> *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    if (!_isCallBackData) { return; }
    
    if (metadataObjects && metadataObjects.count > 0) {//存在数据
        
        if (self.delegate && [self.delegate respondsToSelector:@selector(scannerView:data:)]) {
            
            [self.delegate scannerView:self data:metadataObjects.firstObject];
        }
    }
}


@end
